package com.buydeem.log.serveltlog.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 *
 * @author zengchao
 * @date 2021-05-08 16:56:56
 */
@Slf4j
@Component
public class LogFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info("请求参数:{}",JSON.toJSONString(parameterMap));
        //使用包装Request替换原始的Request
        request = new RepeatReadRequest(request);
        //读取流中的内容
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(request.getInputStream(),out);
        log.info("请求体:{}", out.toString(request.getCharacterEncoding()));
        filterChain.doFilter(request,response);
    }
}
